<template>
  <div class="app-container">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="预评估报告" name="ypg">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          label-width="120px"
          v-show="showSearch"
        >
          <el-form-item label="任务编号" prop="taskNum">
            <el-input
              v-model="queryParams.taskNum"
              placeholder="请输入任务编号"
              clearable
            />
          </el-form-item>
          <el-form-item label="任务名称" prop="taskName">
            <el-input
              v-model="queryParams.taskName"
              placeholder="请输入任务名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="任务状态" prop="taskStatus">
            <el-select
              v-model="queryParams.taskStatus"
              placeholder="请选择任务状态"
              clearable
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="省" prop="province">
            <el-select
              v-model="queryParams.province"
              placeholder="请选择省"
              @change="chooseProvince"
              clearable
              value-key="id"
            >
              <el-option
                v-for="item in provinceData"
                :key="item.id"
                :label="item.name"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="市" prop="city">
            <el-select
              v-model="queryParams.city"
              placeholder="请选择市"
              @change="chooseCity"
              clearable
              value-key="id"
            >
              <el-option
                v-for="item in cityData"
                :key="item.id"
                :label="item.name"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区/县" prop="county">
            <el-select
              v-model="queryParams.county"
              placeholder="请选择区/县"
              @change="chooseCounty"
              clearable
              value-key="id"
            >
              <el-option
                v-for="item in areaData"
                :key="item.id"
                :label="item.name"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label=" ">
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button plain @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" stripe>
          <el-table-column label="任务编号" align="center" prop="taskNum" />
          <el-table-column label="任务名称" align="center" prop="taskName">
            <template #default="scope">
              <el-popover
                placement="top-start"
                title="退回原因"
                :width="200"
                trigger="hover"
                v-if="scope.row.reviewOpinion"
                :content="scope.row.reviewOpinion"
              >
                <template #reference>
                  <span
                    @click="handleCause(scope.row)"
                    style="color: #f56c6c; cursor: pointer"
                    >【退回原因】</span
                  >
                </template>
              </el-popover>
              <span
                @click="handleDeatil(scope.row)"
                style="color: var(--el-color-primary); cursor: pointer"
                >{{ scope.row.taskName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="任务状态" align="center" prop="taskStatus">
            <template #default="scope">
              <span v-if="scope.row.taskStatus == '0'">未分配</span>
              <span v-else-if="scope.row.taskStatus == '1'">进行中</span>
              <span v-else-if="scope.row.taskStatus == '2'">审核中</span>
              <span v-else-if="scope.row.taskStatus == '3'">已结束</span>
            </template>
          </el-table-column>
          <el-table-column label="承担小组" align="center" prop="groupName" />
          <el-table-column
            label="任务地区"
            align="center"
            prop="taskDistrict"
            show-overflow-tooltip
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="300px"
          >
            <template #default="scope">
              <div
                v-if="
                  scope.row.taskStatus == '2' || scope.row.taskStatus == '3'
                "
              >
                <el-button type="text" @click="handleDownload(scope.row)"
                  >报告下载</el-button
                >
              </div>
              <div v-else>
                <el-button type="text" @click="handleCreat(scope.row)"
                  >生成报告</el-button
                >
                <el-button type="text" @click="handleUpload(scope.row)"
                  >报告上传</el-button
                >
                <el-button type="text" @click="handleDownload(scope.row)"
                  >报告下载</el-button
                >
                <el-button
                  type="text"
                  @click="handleReview(scope.row)"
                  v-if="scope.row.reportStatus == '2'"
                  >提交审核</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.page"
          v-model:limit="queryParams.rows"
          @pagination="getList"
        />
      </el-tab-pane>
      <el-tab-pane label="现场调查报告" name="xcdc">
        <el-form
          :model="queryParams"
          ref="queryRefXcdc"
          :inline="true"
          label-width="120px"
          v-show="showSearch"
        >
          <el-form-item label="任务编号" prop="taskNum">
            <el-input
              v-model="queryParams.taskNum"
              placeholder="请输入任务编号"
              clearable
            />
          </el-form-item>
          <el-form-item label="任务名称" prop="taskName">
            <el-input
              v-model="queryParams.taskName"
              placeholder="请输入任务名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="省" prop="province">
            <el-select
              v-model="queryParams.province"
              placeholder="请选择省"
              @change="chooseProvince"
              clearable
              value-key="id"
            >
              <el-option
                v-for="item in provinceData"
                :key="item.id"
                :label="item.name"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="市" prop="city">
            <el-select
              v-model="queryParams.city"
              placeholder="请选择市"
              @change="chooseCity"
              clearable
              value-key="id"
            >
              <el-option
                v-for="item in cityData"
                :key="item.id"
                :label="item.name"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区/县" prop="county">
            <el-select
              v-model="queryParams.county"
              placeholder="请选择区/县"
              @change="chooseCounty"
              clearable
              value-key="id"
            >
              <el-option
                v-for="item in areaData"
                :key="item.id"
                :label="item.name"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label=" ">
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button plain @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList1"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" stripe>
          <el-table-column label="任务编号" align="center" prop="taskNum" />
          <el-table-column label="任务名称" align="center" prop="taskName">
            <template #default="scope">
              <el-popover
                placement="top-start"
                title="退回原因"
                :width="200"
                trigger="hover"
                v-if="scope.row.reviewOpinion"
                :content="scope.row.reviewOpinion"
              >
                <template #reference>
                  <span
                    @click="handleCause(scope.row)"
                    style="color: #f56c6c; cursor: pointer"
                    >【退回原因】</span
                  >
                </template>
              </el-popover>
              <span
                @click="xcdxDeatil(scope.row.id)"
                style="color: var(--el-color-primary); cursor: pointer"
                >{{ scope.row.taskName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="承担小组" align="center" prop="groupName" />
          <el-table-column
            label="任务地区"
            align="center"
            prop="taskDistrict"
            show-overflow-tooltip
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="300px"
          >
            <template #default="scope">
              <div
                v-if="
                  scope.row.taskStatus == '2' || scope.row.taskStatus == '3'
                "
              >
                <el-button type="text" @click="handleDownload(scope.row)"
                  >报告下载</el-button
                >
              </div>
              <div v-else>
                <el-button type="text" @click="handleCreat(scope.row)"
                  >生成报告</el-button
                >
                <el-button type="text" @click="handleUpload(scope.row)"
                  >报告上传</el-button
                >
                <el-button type="text" @click="handleDownload(scope.row)"
                  >报告下载</el-button
                >
                <el-button
                  type="text"
                  @click="handleReview(scope.row)"
                  v-if="scope.row.reportStatus == '2'"
                  >提交审核</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.page"
          v-model:limit="queryParams.rows"
          @pagination="getList1"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 查看现场调查报告详情弹出框 -->
    <el-dialog
      v-model="openDetail"
      title="查看任务"
      width="900px"
      append-to-body
    >
      <p class="dialogTitle">查看任务</p>
      <DetailAssess :detilList="detilList" />
    </el-dialog>

    <!-- 预评估报告编辑弹出框 -->
    <el-dialog :title="title" v-model="open" append-to-body @close="cancel">
      <div v-loading="reportLoading">
        <h2>{{ form.taskName }}</h2>
        <h3><span></span>系统生成</h3>
        <table class="tableport">
          <tr>
            <td class="title">简本报告</td>
            <td class="content">
              <template v-if="formData.defaultSimpleReportName != ''">
                <el-link
                  @click="
                    handleDownloadPort('1', '1', formData.defaultSimpleReportName)
                  "
                  :underline="false"
                >
                  {{ formData.defaultSimpleReportName }}
                </el-link>
              </template>
              <div class="button" v-if="!isDownload">
                <el-button
                  type="primary"
                  @click="openCreateDialog('1')"
                  v-if="!formData.defaultSimpleReportName"
                  >生成报告</el-button
                >
                <el-button
                  type="primary"
                  @click="openCreateDialog('1')"
                  v-else
                  >重新生成</el-button
                >
              </div>
            </td>
          </tr>
          <tr>
            <td class="title">详本报告</td>
            <td class="content">
              <template v-if="formData.defaultMinuteReportName">
                <el-link
                  @click="
                    handleDownloadPort('2', '1', formData.defaultMinuteReportName)
                  "
                  :underline="false"
                >
                  {{ formData.defaultMinuteReportName }}
                </el-link>
              </template>
              <div class="button" v-if="!isDownload">
                <el-button
                  type="primary"
                  @click="openCreateDialog('2')"
                  v-if="!formData.defaultMinuteReportName"
                  >生成报告</el-button
                >
                <el-button
                  type="primary"
                  @click="openCreateDialog('2')"
                  v-else
                  >重新生成</el-button
                >
              </div>
            </td>
          </tr>
        </table>
        <h3 style="display: inline-block"><span></span> 终版报告上传</h3>
        <p style="float: right">
          <el-link type="primary" :underline="false" @click="viewHistoricalVer">历史版本查看</el-link>
        </p>
        <table class="tableport">
          <tr>
            <td class="title">简本报告</td>
            <td class="content">
              <template v-if="formData.userUploadSimpleReportName">
                <el-link
                  @click="
                    handleDownloadPort(
                      '1',
                      '2',
                      formData.userUploadSimpleReportName
                    )
                  "
                  :underline="false"
                >
                  {{ formData.userUploadSimpleReportName }}
                </el-link>
              </template>
              <div class="button" v-if="!isDownload">
                <FileUpload
                  ref="fileUpload"
                  :isShowTip="false"
                  :isShow="!formData.userUploadSimpleReportName"
                  v-model="form.fileList"
                  :uploadFileUrl="formData.reportPath"
                  :taskId="form.taskId"
                  dataSource="2"
                  type="1"
                  @uploadSuccess="uploadSuccess"
                />
              </div>
            </td>
          </tr>
          <tr>
            <td class="title">简本报告上传时间</td>
            <td class="content">
              <span>{{ formData.simpleReportUploadTime }}</span>
            </td>
          </tr>
          <tr>
            <td class="title">详本报告</td>
            <td class="content">
              <template v-if="formData.userUploadMinuteReportName">
                <el-link
                  @click="
                    handleDownloadPort(
                      '2',
                      '2',
                      formData.userUploadMinuteReportName
                    )
                  "
                  :underline="false"
                >
                  {{ formData.userUploadMinuteReportName }}
                </el-link>
              </template>
              <div class="button" v-if="!isDownload">
                <FileUpload
                  ref="fileUpload"
                  :isShowTip="false"
                  :isShow="!formData.userUploadMinuteReportName"
                  v-model="form.fileList"
                  :uploadFileUrl="formData.reportPath"
                  :taskId="form.taskId"
                  dataSource="2"
                  type="2"
                  @uploadSuccess="uploadSuccess"
                />
              </div>
            </td>
          </tr>
          <tr>
            <td class="title">详本报告上传时间</td>
            <td class="content">
              <span>{{ formData.minuteReportUploadTime }}</span>
            </td>
          </tr>
        </table>
        <p></p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button plain @click="cancel(1)">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 生成、重新生成弹框 -->
    <el-dialog
      :title="createReportTitle"
      v-model="createReport"
      append-to-body
      @close="cancelCreatReport"
    >
      <div style="padding: 8px 8px 0">
        <h3 style="font-size: 1rem">请选择报告使用的预评估结果:</h3>
        <el-radio-group v-model="form.dataSource">
          <el-radio label="2">系统计算结果</el-radio>
          <el-radio label="1">【预评估结果上传】的结果</el-radio>
        </el-radio-group>
        <h3 style="font-size: 1rem">请选择报告模板:</h3>
        <el-form :inline="true" :model="reportModel" class="demo-form-inline">
          <el-form-item
            label="简本报告"
            style="margin-bottom: 0"
            v-if="createReportType == '1'"
          >
            <el-select v-model="reportModel.simpleReport" placeholder="请选择">
              <el-option
                v-for="item in reportModel.simpleReportOption"
                :key="item.id"
                :label="item.rtName"
                :value="item.attachId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="详本报告"
            style="margin-bottom: 0"
            v-if="createReportType == '2'"
          >
            <el-select v-model="reportModel.minuteReport" placeholder="请选择">
              <el-option
                v-for="item in reportModel.minuteReportOption"
                :key="item.id"
                :label="item.rtName"
                :value="item.attachId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <h3 style="font-size: 1rem">
          请选择报告统计预评估结果时的行政区划级别:
        </h3>
        <el-radio-group v-model="form.administrativeLevel">
          <el-radio label="2">按区县</el-radio>
          <el-radio label="1">按地市</el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="createPort(createReportType)">生成</el-button>
          <el-button plain @click="cancelCreatReport">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 现场调查报告 -->
    <el-dialog :title="title" v-model="xcdcOpen" append-to-body @close="cancel">
      <h2>{{ form.taskName }}</h2>
      <h3><span></span>报告模板选择</h3>
      <el-form :inline="true" :model="reportModel" class="demo-form-inline">
        <el-form-item label="现场调查报告" style="margin-bottom: 0">
          <el-select v-model="reportModel.xcdcReport" placeholder="请选择">
            <el-option
              v-for="item in reportModel.xcdcReportOption"
              :key="item.id"
              :label="item.rtName"
              :value="item.attachId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <h3><span></span>系统生成</h3>
      <table class="tableport">
        <tr>
          <td class="title">现场调查报告</td>
          <td class="content">
            <template v-if="formData.defaultReportName != ''">
              <el-link
                @click="downloadPort('1', formData.defaultReportName)"
                :underline="false"
              >
                {{ formData.defaultReportName }}
              </el-link>
            </template>
            <div class="button" v-if="!isDownload">
              <el-button
                type="primary"
                @click="creatSampling"
                v-if="!formData.defaultReportName"
                >生成报告</el-button
              >
              <el-button type="primary" @click="creatSampling" v-else>重新生成</el-button>
            </div>
          </td>
        </tr>
      </table>
      <h3 style="display: inline-block"><span></span>终版报告上传</h3>
      <p style="float: right">
        <el-link type="primary" :underline="false" @click="viewHistoricalVer"
          >历史版本查看</el-link
        >
      </p>
      <table class="tableport">
        <tr>
          <td class="title">现场调查报告</td>
          <td class="content">
            <template v-if="formData.userUploadReportName">
              <el-link
                @click="downloadPort('2', formData.userUploadReportName)"
                :underline="false"
              >
                {{ formData.userUploadReportName }}
              </el-link>
            </template>
            <div class="button" v-if="!isDownload">
              <FileUpload
                ref="fileUpload"
                :isShowTip="false"
                reportType="xcdc"
                :isShow="!formData.userUploadReportName"
                v-model="form.fileList"
                :uploadFileUrl="formData.reportPath"
                :taskId="form.taskId"
                type="1"
                @uploadSuccess="uploadSuccess"
              />
            </div>
          </td>
        </tr>
        <tr>
          <td class="title">上传时间</td>
          <td class="content">
            <span>{{ formData.reportUploadTime }}</span>
          </td>
        </tr>
      </table>
      <p></p>
      <template #footer>
        <div class="dialog-footer">
          <el-button plain @click="cancel">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 上传进度展示 -->
    <el-dialog
      v-model="openCreate"
      title="正在生成报告"
      width="400px"
      :close-on-click-modal="false"
      append-to-body
      :show-close="false"
    >
      <p></p>
      <div class="demo-progress">
        <el-progress :percentage="percentages" />
      </div>
      <div class="footer">
        <el-button plain @click="cancelUpload">取消生成</el-button>
      </div>
    </el-dialog>
    <!-- 历史版本查看 -->
    <el-dialog
      v-model="openViewHis"
      title="历史版本查看"
      width="850px"
      append-to-body
    >
      <p></p>
      <el-table v-loading="loading" :data="dataHistoryList" stripe>
        <el-table-column label="序号" align="center" type="index" width="60">
          <template #default="scope">
            <span v-text="getIndex(scope.$index)"></span>
          </template>
        </el-table-column>

        <el-table-column
          label="报告类型"
          align="center"
          prop="type"
          v-if="activeName == 'ypg'"
        >
          <template #default="scope">
            <span v-if="scope.row.type == '1'">简本报告</span>
            <span v-else-if="scope.row.type == '2'">详本报告</span>
          </template>
        </el-table-column>
        <el-table-column
          label="报告名称"
          align="center"
          prop="reportName"
          width="360"
        >
          <template #default="scope">
            <el-button
              type="text"
              @click="handleDownloadHistoryPort(scope.row)"
              >{{ scope.row.reportName }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          label="上传人"
          align="center"
          prop="uploadUserName"
          width="100"
        />
        <el-table-column
          label="上传时间"
          align="center"
          prop="uploadTime"
          width="200"
        />
        <!--<el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
                    <template #default="scope">
                    <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>-->
      </el-table>
      <pagination
        v-show="totalHis > 0"
        :total="totalHis"
        v-model:page="queryParamsHis.page"
        v-model:limit="queryParamsHis.rows"
        @pagination="getHistoryList"
      />
      <p></p>
      <div class="footer">
        <el-button plain @click="openViewHis = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="reportManger">
import { ElMessageBox } from "element-plus";
import { getProvince, getChildArea } from "@/api/system/division";
import {
  getAllList,
  getReport,
  reportCreat,
  canceCreat,
  detailReportCreat,
  getHisList,
  submitReview,
  getSamplingReport,
  getSamplingReportInfo,
  creatSamplingReport,
  getSamplingHisList,
  getReportTemplateByType,
  cancelSamplingCreat,
} from "@/api/resultManag/reportManger.js";
import FileUpload from "./FileUpload/index.vue";
import DetailAssess from "@/views/taskmanage/sceneexamine/detailAssess.vue";
import { detailTask } from "@/api/taskmanage/sceneExame";
const { proxy } = getCurrentInstance();

const router = useRouter();
const dataList = ref([]);
const dataHistoryList = ref([]);
const loading = ref(false);
const open = ref(false);
const xcdcOpen = ref(false);
const openCreate = ref(false);
const openViewHis = ref(false);
const total = ref(0);
const totalHis = ref(0);
const title = ref("");
const showSearch = ref(true);
const percentages = ref();
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
const options = [
  { value: "0", label: "未分配" },
  { value: "1", label: "进行中" },
  { value: "2", label: "审核中" },
  { value: "3", label: "已结束" },
];
const activeName = ref("ypg");
const reportModel = reactive({
  simpleReport: "",
  simpleReportOption: [],
  minuteReport: "",
  minuteReportOption: [],
  xcdcReport: "",
  xcdcReportOption: [],
});

const data = reactive({
  form: {
    administrativeLevel: "0",
    dataSource: 2,
    taskName: null,
    fileList: [],
  },
  formData: {},
  queryParams: {
    page: 1,
    rows: 10,
    taskNum: undefined,
    taskName: undefined,
    taskStatus: undefined,
    province: undefined,
    city: undefined,
    county: undefined,
  },
  queryParamsHis: {
    page: 1,
    rows: 10,
    id: undefined,
  },
});
const { queryParams, queryParamsHis, form, formData } = toRefs(data);
const createReportTitle = ref("");
const createReport = ref(false);
const createReportType = ref("");

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  if (activeName.value == "ypg") {
    getList();
  } else {
    getList1();
  }
}

/** 重置按钮操作 */
function resetQuery() {
  dataList.value = [];
  cityData.value = [];
  areaData.value = [];
  if (activeName.value == "ypg") {
    proxy.resetForm("queryRef");
  } else {
    proxy.resetForm("queryRefXcdc");
  }
  handleQuery();
}

// 重置表单
function reset() {
  formData.value = {};
  form.value = {
    administrativeLevel: "0",
    dataSource: 2,
    taskName: undefined,
    taskId: undefined,
  };
}
function handleClick(tab) {
  dataList.value = [];
  total.value = 0;
  if (tab.props.name == "ypg") {
    getList();
  } else {
    getList1();
  }
}

/** 查询报告任务列表 */
function getList() {
  loading.value = true;
  getAllList(queryParams.value).then((response) => {
    dataList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 预评估任务列表
function getList1() {
  loading.value = true;
  getSamplingReport(queryParams.value).then((response) => {
    dataList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 打开 生成报告
async function handleCreat(row) {
  reset();
  form.value.taskName = row.taskName;
  form.value.taskId = row.id;
  form.value.taskCode = row.taskNum;
  queryParamsHis.value.id = row.id;
  if (activeName.value == "ypg") {
    title.value = "预评估报告管理-生成报告";
    open.value = true;
    let resSimple = await getReportTemplateByType("简本报告");
    let resMinute = await getReportTemplateByType("详本报告");
    reportModel.simpleReportOption = resSimple.data;
    reportModel.minuteReportOption = resMinute.data;
    let resForm = await getReport(row.id);
    formData.value = resForm.data;
    form.value.administrativeLevel = resForm.data.administrativeLevel;
    form.value.dataSource = resForm.data.dataSource;
    if (resForm.data.simplifiedReportTemplate) {
      let selectInfo = reportModel.simpleReportOption.filter(
        (item) => item.rtName == resForm.data.simplifiedReportTemplate
      );
      selectInfo.length > 0 &&
        (reportModel.simpleReport = selectInfo[0].attachId);
    }
    if (resForm.data.deReportTemplate) {
      let selectInfo = reportModel.minuteReportOption.filter(
        (item) => item.rtName == resForm.data.deReportTemplate
      );
      selectInfo.length > 0 &&
        (reportModel.minuteReport = selectInfo[0].attachId);
    }
  } else if (activeName.value == "xcdc") {
    title.value = "现场调查报告管理-生成报告";
    xcdcOpen.value = true;
    let resXcdc = await getReportTemplateByType("现场调查报告");
    reportModel.xcdcReportOption = resXcdc.data;
    let resForm = await getSamplingReportInfo(row.id);
    formData.value = resForm.data;
    form.value.administrativeLevel = resForm.data.administrativeLevel;
    form.value.dataSource = resForm.data.dataSource;
    if (resForm.data.modelName) {
      let selectInfo = reportModel.xcdcReportOption.filter(
        (item) => item.rtName == resForm.data.modelName
      );
      if (selectInfo.length > 0) {
        reportModel.xcdcReport = selectInfo[0].attachId;
      }
    }
  }
}
// 打开 报告上传
async function handleUpload(row) {
  reset();
  form.value.taskName = row.taskName;
  form.value.taskId = row.id;
  form.value.taskCode = row.taskNum;
  queryParamsHis.value.id = row.id;
  if (activeName.value == "ypg") {
    title.value = "预评估报告管理-报告上传";
    open.value = true;
    let resSimple = await getReportTemplateByType("简本报告");
    let resMinute = await getReportTemplateByType("详本报告");
    reportModel.simpleReportOption = resSimple.data;
    reportModel.minuteReportOption = resMinute.data;
    let resForm = await getReport(row.id);
    formData.value = resForm.data;
    if (resForm.data.simplifiedReportTemplate) {
      let selectInfo = reportModel.simpleReportOption.filter(
        (item) => item.rtName == resForm.data.simplifiedReportTemplate
      );
      selectInfo.length > 0 &&
        (reportModel.simpleReport = selectInfo[0].attachId);
    }
    if (resForm.data.deReportTemplate) {
      let selectInfo = reportModel.minuteReportOption.filter(
        (item) => item.rtName == resForm.data.deReportTemplate
      );
      selectInfo.length > 0 &&
        (reportModel.minuteReport = selectInfo[0].attachId);
    }
  } else if (activeName.value == "xcdc") {
    title.value = "现场调查报告管理-报告上传";
    xcdcOpen.value = true;
    let resXcdc = await getReportTemplateByType("现场调查报告");
    reportModel.xcdcReportOption = resXcdc.data;
    let resForm = await getSamplingReportInfo(row.id);
    formData.value = resForm.data;
    if (resForm.data.modelName) {
      let selectInfo = reportModel.xcdcReportOption.filter(
        (item) => item.rtName == resForm.data.modelName
      );
      if (selectInfo.length > 0) {
        reportModel.xcdcReport = selectInfo[0].attachId;
      }
    }
  }
}
// 打开 报告下载
const isDownload = ref(false);
const reportLoading = ref(false)
async function handleDownload(row) {
  reset();
  form.value.taskName = row.taskName;
  form.value.taskId = row.id;
  form.value.taskCode = row.taskNum;
  if (activeName.value == "ypg") {
    reportLoading.value = true
    title.value = "预评估报告管理-报告下载";
    open.value = true;
    let resSimple = await getReportTemplateByType("简本报告");
    let resMinute = await getReportTemplateByType("详本报告");
    reportModel.simpleReportOption = resSimple.data;
    reportModel.minuteReportOption = resMinute.data;
    let resForm = await getReport(row.id);
    formData.value = resForm.data;
    if (resForm.data.simplifiedReportTemplate) {
      let selectInfo = reportModel.simpleReportOption.filter(
        (item) => item.rtName == resForm.data.simplifiedReportTemplate
      );
      selectInfo.length > 0 &&
        (reportModel.simpleReport = selectInfo[0].attachId);
    }
    if (resForm.data.deReportTemplate) {
      let selectInfo = reportModel.minuteReportOption.filter(
        (item) => item.rtName == resForm.data.deReportTemplate
      );
      selectInfo.length > 0 &&
        (reportModel.minuteReport = selectInfo[0].attachId);
    }
    reportLoading.value = false
  } else if (activeName.value == "xcdc") {
    title.value = "现场调查报告管理-报告下载";
    xcdcOpen.value = true;
    let resXcdc = await getReportTemplateByType("现场调查报告");
    reportModel.xcdcReportOption = resXcdc.data;
    let resForm = await getSamplingReportInfo(row.id);
    formData.value = resForm.data;
    if (resForm.data.modelName) {
      let selectInfo = reportModel.xcdcReportOption.filter(
        (item) => item.rtName == resForm.data.modelName
      );
      if (selectInfo.length > 0) {
        reportModel.xcdcReport = selectInfo[0].attachId;
      }
    }
  }
  isDownload.value = true;
}
// 提交审核
function handleReview(row) {
  submitReview(row.reportId).then((response) => {
    proxy.$modal.msgSuccess("提交审核成功");
    // getList();
    if (activeName.value == "ypg") {
      getList();
    } else {
      getList1();
    }
  });
}

// 上传成功回调
function uploadSuccess(val) {
  formData.value = val.data;
}

// 获取历史版本
function getHistoryList() {
  if (activeName.value == "ypg") {
    getHisList(queryParamsHis.value).then((response) => {
      dataHistoryList.value = response.data.rows;
      totalHis.value = response.data.total;
    });
  } else {
    getSamplingHisList(queryParamsHis.value).then((response) => {
      dataHistoryList.value = response.data.rows;
      totalHis.value = response.data.total;
    });
  }
}
// 获取序号
function getIndex(index) {
  return (
    (queryParamsHis.value.page - 1) * queryParamsHis.value.rows + index + 1
  );
}
// 历史版本查看
function viewHistoricalVer() {
  openViewHis.value = true;
  getHistoryList();
}
// 生成报告
function openCreateDialog(type) {
  if (type == "1") {
    createReportTitle.value = "生成简本报告";
  } else if (type == "2") {
    createReportTitle.value = "生成详本报告";
  }
  createReportType.value = type;
  createReport.value = true;
  getReport(form.value.taskId).then((res) => {
    if (res.data.simplifiedReportTemplate) {
      let selectInfo = reportModel.simpleReportOption.filter(
        (item) => item.rtName == res.data.simplifiedReportTemplate
      );
      selectInfo.length > 0 &&
        (reportModel.simpleReport = selectInfo[0].attachId);
    }
    if (res.data.deReportTemplate) {
      let selectInfo = reportModel.minuteReportOption.filter(
        (item) => item.rtName == res.data.deReportTemplate
      );
      selectInfo.length > 0 &&
        (reportModel.minuteReport = selectInfo[0].attachId);
    }
    form.value.administrativeLevel = res.data.administrativeLevel;
    form.value.dataSource = res.data.dataSource;
  });
}
function cancelCreatReport() {
  createReport.value = false;
  form.value.dataSource = 2;
  form.value.administrativeLevel = "0";
  reportModel.simpleReport = "";
  reportModel.minuteReport = "";
}
let cancelFunc = {};
function createPort(type) {
  if (typeof cancelFunc.c === "function") {
    cancelFunc.c("取消成功");
  }
  let query = {
    taskId: form.value.taskId,
    dataSource: form.value.dataSource,
    type: type,
    level: form.value.administrativeLevel,
  };
  if (type == "1") {
    if (!reportModel.simpleReport) {
      proxy.$modal.msgWarning("请选择简本报告模板！");
      return;
    }
    query.attachId = reportModel.simpleReport;
    query.simplifiedReportTemplate = reportModel.simpleReportOption.filter(
      (item) => item.attachId == reportModel.simpleReport
    )[0].rtName;
  }
  let detailQuery = {
    taskId: form.value.taskId,
    useType: form.value.dataSource,
    level: form.value.administrativeLevel,
    taskName: form.value.taskName,
  };
  if (type == "2") {
    if (!reportModel.minuteReport) {
      proxy.$modal.msgWarning("请选择详本报告模板！");
      return;
    }
    detailQuery.attachId = reportModel.minuteReport;
    detailQuery.reportName = reportModel.minuteReportOption.filter(
      (item) => item.attachId == reportModel.minuteReport
    )[0].rtName;
  }
  percentages.value = 0;
  openCreate.value = true;

  let startTime = setInterval(() => {
    if (percentages.value < 50) {
      percentages.value += 5;
    }
    if (percentages.value == 50) {
      clearInterval(startTime);
      let conductTime = setInterval(() => {
        if (percentages.value == 95) {
          clearInterval(conductTime);
        }
        if (percentages.value < 96) {
          percentages.value += 2;
        }
      }, 100);
    }
  }, 100);
  if (type == "1") {
    reportCreat(query, cancelFunc)
      .then((res) => {
        percentages.value = 100;
        createReport.value = false;
        openCreate.value = false;
        const { code, data, message } = res;
        if (code == 200 && data) {
          formData.value = res.data;
          clearInterval(startTime);
          proxy.$modal.msgSuccess("简本报告生成成功！");
        } else {
          proxy.$modal.msgError(message);
        }
        // clearInterval(conductTime);
      })
      .catch((err) => {
        openCreate.value = false;
        if (err.message !== "取消成功") {
          cancelFunc.c = null;
        }
      });
  } else if (type == "2") {
    detailReportCreat(detailQuery, cancelFunc)
      .then((res) => {
        console.log(res.data);
        percentages.value = 100;
        createReport.value = false;
        openCreate.value = false;
        const { code, data, message } = res;
        if (code == 200) {
          formData.value = res.data.result;
          clearInterval(startTime);
          if (data.msg == "") {
            ElMessageBox.alert("详本报告生成成功！", "消息", {
              type: "success",
              ElMessageBox: "确定",
              dangerouslyUseHTMLString: true,
              callback: () => {},
            });
          } else {
            ElMessageBox.alert(data.msg, "消息", {
              type: "error",
              ElMessageBox: "确定",
              dangerouslyUseHTMLString: true,
              callback: () => {
                // getList();
              },
            });
          }
          // proxy.$modal.msgSuccess('详本报告生成成功！')
        } else {
          ElMessageBox.alert(message, "消息", {
            type: "error",
            confirmButtonText: "确定",
            dangerouslyUseHTMLString: true,
            callback: () => {},
          });
          // proxy.$modal.msgError(message)
        }
      })
      .catch((err) => {
        openCreate.value = false;
        if (err.message !== "取消成功") {
          cancelFunc.c = null;
        }
      });
  }
}

// 取消生成
function cancelUpload() {
  if (typeof cancelFunc.c === "function") {
    cancelFunc.c("取消成功");
  }
  openCreate.value = false;
  // if (activeName.value == 'ypg') {
  //     const query = {
  //         taskId: form.value.taskId,
  //         type: '1',
  //         level: '1'
  //     }
  //     percentages.value = 0;
  //     canceCreat(query).then(res => {
  //         percentages.value = 0;
  //         proxy.$modal.msgSuccess("取消成功");
  //     })
  // } else if (activeName.value == 'xcdc') {
  //     const query = {
  //         taskName: form.value.taskName,
  //         taskCode: form.value.taskCode,
  //         attachId: reportModel.xcdcReport,
  //         modelName: reportModel.xcdcReportOption.filter(item => item.attachId == reportModel.xcdcReport)[0].rtName
  //     }
  //     percentages.value = 0;
  //     cancelSamplingCreat(query).then(res => {
  //         percentages.value = 0;
  //         proxy.$modal.msgSuccess("取消成功");
  //     })
  // }
}
// 下载文件
function handleDownloadPort(type, def, name) {
  proxy.download(
    "/report/downloadReport",
    {
      reportId: formData.value.id,
      type: type,
      def: def,
    },
    name
  );
}
// 下载历史文件
function handleDownloadHistoryPort(row) {
  if (activeName.value == "ypg") {
    proxy.download(
      "/report/downloadHistoryReport",
      {
        reportId: row.id,
      },
      row.reportName
    );
  } else if (activeName.value == "xcdc") {
    proxy.download(
      "/samplingReport/downloadHistoryReport",
      {
        reportId: row.id,
      },
      row.reportName
    );
  }
}

/** 取消按钮 */
function cancel(num) {
  open.value = false;
  xcdcOpen.value = false;
  isDownload.value = false;
  reset();
  if (num && num == 1) {
    if (activeName.value == "ypg") {
      getList();
    } else {
      getList1();
    }
  }
}

/** 获取省列表 */
function getProvinceData() {
  getProvince().then((response) => {
    provinceData.value = response.data;
  });
}

function chooseProvince(value) {
  queryParams.value.city = null;
  queryParams.value.county = null;
  queryParams.value.province = value.name;
  cityData.value = [];
  areaData.value = [];
  getChildArea(value.id).then((response) => {
    cityData.value = response.data;
  });
}

function chooseCity(value) {
  queryParams.value.city = value.name;
  queryParams.value.county = null;
  areaData.value = [];
  getChildArea(value.id).then((response) => {
    areaData.value = response.data;
  });
}

function chooseCounty(value) {
  queryParams.value.county = value.name;
}
// 任务名称
function handleDeatil(row) {
  // assignSetArthquake 0代表已分配
  // 有子任务的父任务-1parentId为0，children.length为0
  // 无子任务的父任务-2parentId为0，children.length为0
  // 子任务-3 parentId不为0
  // 待分配任务-4
  // assignSetArthquake 0代表已分配
  let pattern = "0";
  if (row.parentId != "0") {
    pattern = "3";
  } else {
    pattern = row.children?.length > 0 ? "1" : "2";
  }
  router.push({
    name: "earthquakeDetail",
    query: {
      taskId: row.id,
      taskType: row.assignSetArthquake || "1",
      pattern,
      metaTitle: row.taskName,
    },
  });
}

// 现场调查报告-生成报告
function creatSampling() {
  if (typeof cancelFunc.c === "function") {
    cancelFunc.c("取消成功");
  }
  if (!reportModel.xcdcReport) {
    proxy.$modal.msgWarning("请选择报告模板！");
    return;
  }
  const data = {
    taskName: form.value.taskName,
    taskCode: form.value.taskCode,
    attachId: reportModel.xcdcReport,
    modelName: reportModel.xcdcReportOption.filter(
      (item) => item.attachId == reportModel.xcdcReport
    )[0].rtName,
  };
  percentages.value = 0;
  openCreate.value = true;
  let startTime = setInterval(() => {
    if (percentages.value < 50) {
      percentages.value += 5;
    }
    if (percentages.value == 50) {
      clearInterval(startTime);
      let conductTime = setInterval(() => {
        if (percentages.value == 95) {
          clearInterval(conductTime);
        }
        if (percentages.value < 96) {
          percentages.value += 2;
        }
      }, 100);
    }
  }, 100);
  creatSamplingReport(data, cancelFunc)
    .then((res) => {
      console.log(res);
      const { code, data, message } = res;
      if (code == 200) {
        percentages.value = 100;
        openCreate.value = false;
        formData.value = res.data.rp;
        clearInterval(startTime);
        if (data.msg == "") {
          ElMessageBox.alert("现场调查报告生成成功！", "消息", {
            type: "success",
            ElMessageBox: "确定",
            dangerouslyUseHTMLString: true,
            callback: () => {},
          });
        } else {
          ElMessageBox.alert(data.msg, "消息", {
            type: "error",
            ElMessageBox: "确定",
            dangerouslyUseHTMLString: true,
            callback: () => {},
          });
        }
        // proxy.$modal.msgSuccess("生成成功");
        // clearInterval(conductTime);
      } else {
        ElMessageBox.alert(message, "消息", {
          type: "error",
          confirmButtonText: "确定",
          dangerouslyUseHTMLString: true,
          callback: () => {},
        });
      }
    })
    .catch((err) => {
      if (err.message !== "取消成功") {
        cancelFunc.c = null;
      }
    });
}
// 现场调查报告-下载报告
function downloadPort(def, name) {
  proxy.download(
    "/samplingReport/downloadReport",
    {
      reportId: formData.value.id,
      def,
    },
    name
  );
}
// 现场调查报告-查看详情
const openDetail = ref(false);
const detilList = ref({});
function xcdxDeatil(id) {
  detailTask({ id }).then((res) => {
    nextTick(() => {
      detilList.value.preAssessTaskEntity = res.data.preAssessTaskEntity;
      detilList.value.memberlist = res.data.memberlist;
      detilList.value.expertlist = res.data.expertlist;
      openDetail.value = true;
    });
  });
}

getProvinceData();
getList();
</script>

<style lang="scss" scoped>
h3 {
  color: #333;
  height: 21px;
  font-size: 14px;
  line-height: 21px;
  display: flex;
  align-items: center;
  font-weight: bold;

  span {
    margin-right: 12px;
    display: inline-block;
    width: 3px;
    height: 14px;
    background: #333;
  }
}

.tableport {
  border-collapse: collapse;
  width: 100%;

  tr {
    height: 54px;

    td {
      border: 1px solid #000;

      &.title {
        text-align: center;
        width: 250px;
        font-weight: 700;
        color: 16px;
      }

      &.content {
        padding: 0px 20px;
        line-height: 54px;

        .button {
          float: right;
          height: 54px;
          vertical-align: middle;
        }
      }
    }
  }
}

.demo-progress .el-progress--line {
  margin: 40px 0;
  // margin-bottom: 15px;
  width: 350px;
}

.footer {
  text-align: center;
}
</style>
